package ggze.esp.controller;


import ggze.actuator.ActuatorController;
import ggze.esp.dao.inter.FspApiDao;
import ggze.esp.dao.inter.FspDataRecordDao;
import ggze.esp.dao.inter.FspLookRecordDao;
import ggze.esp.dao.inter.FspRequestLogDao;
import ggze.esp.entity.FspApi;
import ggze.esp.entity.FspDataRecord;
import ggze.esp.entity.FspLookRecord;
import ggze.esp.entity.FspRequestLog;
import ggze.esp.service.CommonService;
import ggze.loader.Storage;

import ggze.tool.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;

@Controller
public class GouController {
    @Autowired
    private FspApiDao apiDao;
    @Autowired
    private FspDataRecordDao dataRecordDao;
    @Autowired
    private FspLookRecordDao lookRecordDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FspRequestLogDao requestLogDao;
    @Autowired
    private ActuatorController actuatorController;
    @Autowired
    private CommonService commonService;

    @RequestMapping("/vsp")
    public String esp(HttpServletResponse response) throws UnsupportedEncodingException {
        ReturnBody returnBody = new ReturnBody();
        try {
            String originHeader = this.getClientIP(request);
            FspApi api = new FspApi();
            if (originHeader == null) {
                api = null;
            } else {
                api = apiDao.isSelect("F_IP", originHeader);
            }
            if (api != null && api.getF_IS().equals("0")) {
                response.setHeader("Access-Control-Allow-Origin", originHeader);
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            }
            String code = request.getParameter("code");
            String token = request.getParameter("token");
            FspLookRecord lookRecord = lookRecordDao.isSelect("uuid", code);
            String view = lookRecord.getF_MIRROR_CODE();
            if (lookRecord.getF_STATUS().equals("0")) {
                returnBody = commonService.chaekUser(token, code, "look",request);
                if(returnBody.getCode().equals("1")){
                    returnBody.setCode("1");
                    returnBody.setTitle("系统错误!请联系管理员");
                    System.out.println(BeanToJson.toJsonObjectString(returnBody));
                    return "redirect:./vsp?code=1574998957819&spack="+URLEncoder.encode(returnBody.getTitle());
                }
                if(returnBody.getCode().equals("0")){
                    if (view.equals("2")) {
                        return lookRecord.getF_PAGE_VIEW();
                    } else {
                        response.sendRedirect(lookRecord.getF_PAGE_VIEW());
                    }
                }
            } else {
                returnBody.setCode("1");
                returnBody.setTitle("当前视图已被禁用!");
                return "redirect:./vsp?code=1574998957819&spack="+ URLEncoder.encode(returnBody.getTitle());
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            returnBody.setCode("1");
            returnBody.setTitle("系统错误!请联系管理员");
            System.out.println(BeanToJson.toJsonObjectString(returnBody));
            return "redirect:./vsp?code=1574998957819&spack="+URLEncoder.encode(returnBody.getTitle());
        }
    }

    @RequestMapping(value = "/dsp" ,method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String dsp(HttpServletResponse response, @RequestBody JSONObject jsonObject){
        ReturnBody returnBody = new ReturnBody();
        try {
            String originHeader = this.getClientIP(request);
            FspApi api = new FspApi();
            if (originHeader == null) {
                api = null;
            } else {
                api = apiDao.isSelect("F_IP", originHeader);
            }
            if (Storage.getObj().getConfig().get("interfaceSwitch").equals("true")) {
                if (api != null && api.getF_IS().equals("0")) {
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                    response.setHeader("Access-Control-Max-Age", "3600");
                    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
                }
            } else {
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            }
            String token = request.getHeader("token");
            String webName = Storage.getObj().getConfig().get("mirrorName");
            String code = request.getParameter("code");
            FspDataRecord dataRecord = dataRecordDao.isSelect("uuid", code);
            if (dataRecord.getF_STATUS().equals("0")) {
                returnBody = commonService.chaekUser(token, code, "api",request);
                if(returnBody.getCode().equals("1")){
                    return  BeanToJson.toJsonObjectString(returnBody);
                }

                FspRequestLog requestLog = new FspRequestLog();
                Enumeration er = request.getHeaderNames();//获取请求头的所有name值


                String json = jsonObject.toString();

                StringBuilder herder = new StringBuilder();
                while (er.hasMoreElements()) {
                    String name = (String) er.nextElement();
                    String value = request.getHeader(name);
                    herder.append("  " + name + "=" + value);
                }
                requestLog.setF_HEADERS(herder.toString());
                String time = TimeUtils.getTimeFormat();
                requestLog.setF_CREATE_TIME(time);
                requestLog.setF_METHOD_TIME(time);
                requestLog.setUuid("");
                requestLog.setF_JS_JSON(json);
                Long times_1 = Long.parseLong(TimeUtils.getTimeStmp());

                String req = "";
                try {
                    req = ParHttpRequest.sendPost("http://localhost" + webName + "/" + dataRecord.getF_URI(), jsonObject);
                    requestLog.setF_CODE("0");
                } catch (Exception e) {
                    requestLog.setF_CODE("1");
                }


                Long times_2 = Long.parseLong(TimeUtils.getTimeStmp());
                Long diff = times_2 - times_1;
                diff = (diff % (1000 * 60)) / 1000;
                requestLog.setF_BACK_TIME(String.valueOf(diff));
                requestLog.setF_FH_JSON(req.toString());

                requestLog.setF_API_NAME(dataRecord.getF_SPACK());
                if (Storage.getObj().getConfig().get("localhostLog").equals("true") && request.getHeader("host").indexOf("localhost") >= 0) {
                    try {
                        actuatorController.execute(requestLog, "add", requestLogDao);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (request.getHeader("host").indexOf("localhost") < 0) {
                    try {
                        actuatorController.execute(requestLog, "add", requestLogDao);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return req;
            } else {
                returnBody.setCode("1");
                returnBody.setTitle("此api已经被禁用！请联系开发者");
                return BeanToJson.toJsonObjectString(returnBody);
            }
        }catch (Exception e){
           returnBody.setCode("1");
           returnBody.setTitle("token失效！重新登录");
           return BeanToJson.toJsonObjectString(returnBody);
        }
    }

    private String getClientIP(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }
        XFor = Xip;
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

}
